<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${ctx}/common/plugins/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctx}/common/plugins/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="${ctx}/common/common.css" media="all">
    <script src="${ctx}/common/plugins/jquery-1.10.2.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="${ctx}/common/plugins/layuiadmin/layui/layui.js"></script>

    <style type="text/css">
        .rowtop {
            padding: 10px;
        }


        .file-preview {
            margin-top: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .file-item {
            position: relative;
            width: 100px;
            height: 120px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            padding: 5px;
            text-align: center;
            background: #f8f8f8;
        }

        .file-icon {
            font-size: 40px;
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .file-icon.img {
            color: #e74c3c;
        }

        .file-icon.excel {
            color: #27ae60;
        }

        .file-icon.pdf {
            color: #e67e22;
        }

        .file-icon.word {
            color: #3498db;
        }

        .file-icon.other {
            color: #7f8c8d;
        }

        .file-name {
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 5px;
        }

        .file-remove {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #ff5722;
            color: white;
            text-align: center;
            line-height: 20px;
            cursor: pointer;
            font-size: 12px;
            display: none;
        }

        .file-item:hover .file-remove {
            display: block;
        }

        .upload-status {
            margin-top: 10px;
            font-size: 13px;
            color: #666;
        }

        .upload-btn-group {
            margin-top: 15px;
        }

        .supported-types {
            margin-top: 10px;
            font-size: 13px;
            color: #666;
        }

        .file-preview-img {
            max-width: 100px;
            max-height: 70px;
            object-fit: contain;
        }
    </style>
</head>
<body>
<form class="layui-form layui-container" method="post" action="${ctx}/enterprise/${action}"
      enctype="multipart/form-data" style="background-color: white;">
    <input type="hidden" name="id" value="${entity.id}"/>
    <input type="hidden" name="companyId" value="${companyId}"/>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">品名<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="productName" required value="${entity.productName}" lay-verify="required"
                       placeholder="请输入品名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-md5">
            <label class="layui-form-label">批准文号<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="approvalNumber" lay-verify="required" value="${entity.approvalNumber}"
                       placeholder="请输入批准文号" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">规格<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="specification" required value="${entity.specification}" lay-verify="required"
                       placeholder="请输入规格" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-md5">
            <label class="layui-form-label">剂型<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="dosageForm" lay-verify="required" value="${entity.dosageForm}"
                       placeholder="请输入剂型" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">保健功能<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="healthFunction" required value="${entity.healthFunction}" lay-verify="required"
                       placeholder="请输入保健功能" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-md5">
            <label class="layui-form-label">企业标准<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="enterpriseStandard" lay-verify="required" value="${entity.enterpriseStandard}"
                       placeholder="请输入企业标准" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">申报材料<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="applicationMaterials" required value="${entity.applicationMaterials}"
                       lay-verify="required" placeholder="请输入申报材料" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-col-md5">
            <label class="layui-form-label">变更情况<span style="color: red">*</span></label>
            <div class="layui-input-block">
                <input type="text" name="revisionStatus" lay-verify="required" value="${entity.revisionStatus}"
                       placeholder="请输入变更情况" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">在产产品型式检验报告<span style="color: red">*</span></label>

            <%--                <c:if test="${!empty entity.typeReport && fn:length(entity.typeReport)>0  && entity.typeReport != 'null' }">--%>
            <%--                    <img src="${ctx}${entity.typeReport}" class="typeReportImg" style="width: 100px;height: 100px;">--%>
            <%--                </c:if>--%>

            <div class="layui-input-block">
                <div class="file-upload-container">
                    <input type="file" name="file" id="fileInput" style="display: none;"
                           accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx">
                    <button type="button" class="layui-btn" id="uploadBtn">
                        <i class="layui-icon">&#xe67c;</i>选择文件
                    </button>
                </div>
                <div class="file-preview" id="filePreview">
                    <c:if test="${!empty entity.typeReport && fn:length(entity.typeReport)>0 && entity.typeReport != 'null'}">
                        <div class="file-item">
                            <div class="file-remove" onclick="removeUploadedFile()"><i
                                    class="layui-icon">&#x1006;</i></div>
                            <div class="file-icon">
                                <c:choose>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileType == 'image'}">
                                        <img src="${ctx}/files/${fileInfo.serverFileName}"
                                             class="file-preview-img"
                                             onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                                        <div style="display:none; color: #999; font-size: 12px;">图片加载失败
                                        </div>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileType == 'excel'}">
                                        <i class="fas fa-file-excel excel"></i>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileType == 'pdf'}">
                                        <div class="file-icon pdf">
                                            <i class="fas fa-file-pdf "></i>
                                        </div>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileType == 'word'}">
                                        <i class="fas fa-file-word word"></i>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileType == 'text'}">
                                        <i class="fas fa-file-alt text"></i>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true}">
                                        <i class="fas fa-file other"></i>
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == false}">
                                        <i class="fas fa-exclamation-triangle" style="color: #ff5722;"></i>
                                    </c:when>
                                    <c:otherwise>
                                        <c:choose>
                                            <c:when test="${fn:endsWith(eentity.typeReport, '.jpg') || fn:endsWith(eentity.typeReport, '.png') || fn:endsWith(eentity.typeReport, '.gif')}">
                                                <img src="${ctx}/files/${fileInfo.serverFileName}"
                                                     class="file-preview-img"
                                                     onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                                                <div style="display:none; color: #999; font-size: 12px;">
                                                    图片加载失败
                                                </div>
                                            </c:when>
                                            <c:when test="${fn:endsWith(eentity.typeReport, '.xls') || fn:endsWith(eentity.typeReport, '.xlsx')}">
                                                <i class="fas fa-file-excel excel"></i>
                                            </c:when>
                                            <c:when test="${fn:endsWith(eentity.typeReport, '.pdf')}">
                                                <div class="file-icon pdf">
                                                    <i class="fas fa-file-pdf "></i>
                                                </div>
                                            </c:when>
                                            <c:when test="${fn:endsWith(eentity.typeReport, '.doc') || fn:endsWith(eentity.typeReport, '.docx')}">
                                                <i class="fas fa-file-word word"></i>
                                            </c:when>
                                            <c:otherwise>
                                                <i class="fas fa-file other"></i>
                                            </c:otherwise>
                                        </c:choose>
                                    </c:otherwise>
                                </c:choose>
                            </div>
                            <div class="file-name"
                                 title="${!empty fileInfo ? fileInfo.fileName : '已上传文件'}">
                                <c:choose>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileName != null}">
                                        ${fileInfo.fileName}
                                    </c:when>
                                    <c:when test="${!empty fileInfo && fileInfo.exists == false}">
                                        <span style="color: #ff5722;">${fileInfo.fileName}</span>
                                    </c:when>
                                    <c:otherwise>
                                        已上传文件
                                    </c:otherwise>
                                </c:choose>
                            </div>
                            <c:if test="${!empty fileInfo && fileInfo.exists == true && fileInfo.fileSize != null}">
                                <div class="file-size" style="font-size: 10px; color: #999; margin-top: 2px;">
                                    <c:choose>
                                        <c:when test="${fileInfo.fileSize > 1048576}">
                                            <fmt:formatNumber value="${fileInfo.fileSize / 1048576.0}"
                                                              maxFractionDigits="1"/>MB
                                        </c:when>
                                        <c:when test="${fileInfo.fileSize > 1024}">
                                            <fmt:formatNumber value="${fileInfo.fileSize / 1024.0}"
                                                              maxFractionDigits="1"/>KB
                                        </c:when>
                                        <c:otherwise>
                                            ${fileInfo.fileSize}B
                                        </c:otherwise>
                                    </c:choose>
                                </div>
                            </c:if>
                        </div>
                    </c:if>
                </div>

            </div>
        </div>
        <div class="layui-col-md5">
            <label class="layui-form-label">在产产品的批次检验报告<span style="color: red">*</span></label>
            <div class="layui-input-block" id="batchReportImg">
                <button type="button" class="layui-btn" id="batchReportUpload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
                <input type="file" name="batchReportFile" id="batchReportFile" style="display: none;" accept="image/*">
                <c:if test="${!empty entity.batchReport && fn:length(entity.batchReport)>0  && entity.batchReport != 'null' }">
                    <img src="${ctx}${entity.batchReport}" class="batchReportImg" style="width: 100px;height: 100px;">
                </c:if>
            </div>
        </div>
    </div>
    <div class="layui-row rowtop">
        <div class="layui-col-md5">
            <label class="layui-form-label">包装图片<span style="color: red">*</span></label>
            <div class="layui-input-block" id="packagingImg">
                <button type="button" class="layui-btn" id="packagingImgUpload">
                    <i class="layui-icon">&#xe67c;</i>上传图片
                </button>
                <input type="file" name="packagingImgFile" id="packagingImgFile" style="display: none;"
                       accept="image/*">
                <c:if test="${!empty entity.packagingImg && fn:length(entity.packagingImg)>0  && entity.packagingImg != 'null' }">
                    <img src="${ctx}${entity.packagingImg}" class="packagingImg" style="width: 100px;height: 100px;">
                </c:if>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" id="formBtn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            <button type="button" id="rollback" class="layui-btn layui-btn-primary">返回</button>
        </div>
    </div>
</form>

<script>
    // 使用 Layui 的表单模块和layer模块
    layui.use(['form', 'laydate', 'upload', 'layer'], function () {
        var form = layui.form;
        var $ = layui.$;
        var layer = layui.layer;
        // 文件选择按钮点击事件
        $('#uploadBtn').click(function () {
            $('#fileInput').click();
        });
        // 文件选择事件
        $('#fileInput').change(function () {
            var file = this.files[0];
            if (file) {
                // 显示文件预览
                $("#filePreview").html('');
                var fileIcon = 'other';
                var iconClass = 'fas fa-file';

                if (file.type.indexOf('image') !== -1) {
                    // 如果是图片，显示图片预览
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $("#filePreview").append('<div class="file-item">' +
                            '<div class="file-remove" onclick="clearFile()"><i class="layui-icon">&#x1006;</i></div>' +
                            '<div class="file-icon"><img src="' + e.target.result + '" class="file-preview-img"></div>' +
                            '<div class="file-name" title="' + file.name + '">' + file.name + '</div>' +
                            '</div>');
                    };
                    reader.readAsDataURL(file);
                } else {
                    // 根据文件类型显示对应图标
                    if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx') || file.type.indexOf('spreadsheet') !== -1) {
                        fileIcon = 'excel';
                        iconClass = 'fas fa-file-excel';
                    } else if (file.name.endsWith('.pdf') || file.type.indexOf('pdf') !== -1) {
                        console.log(2)
                        fileIcon = 'pdf';
                        iconClass = 'fas fa-file-pdf';
                    } else if (file.name.endsWith('.doc') || file.name.endsWith('.docx') || file.type.indexOf('word') !== -1) {
                        fileIcon = 'word';
                        iconClass = 'fas fa-file-word';
                    }

                    $("#filePreview").append('<div class="file-item">' +
                        '<div class="file-remove" onclick="clearFile()"><i class="layui-icon">&#x1006;</i></div>' +
                        '<div class="file-icon ' + fileIcon + '"><i class="' + iconClass + '"></i></div>' +
                        '<div class="file-name" title="' + file.name + '">' + file.name + '</div>' +
                        '</div>');
                }
            }
        });
        // 监听表单提交
        form.on('submit(formDemo)', function (data) {
            // 验证必填字段
            var productName = $('input[name="productName"]').val();
            var approvalNumber = $('input[name="approvalNumber"]').val();
            var specification = $('input[name="specification"]').val();
            var dosageForm = $('input[name="dosageForm"]').val();
            var healthFunction = $('input[name="healthFunction"]').val();
            var enterpriseStandard = $('input[name="enterpriseStandard"]').val();
            var applicationMaterials = $('input[name="applicationMaterials"]').val();
            var revisionStatus = $('input[name="revisionStatus"]').val();

            // 检查必填字段
            if (!productName || !approvalNumber || !specification || !dosageForm ||
                !healthFunction || !enterpriseStandard || !applicationMaterials || !revisionStatus) {
                layer.msg('请填写所有必填字段！', {icon: 2});
                return false;
            }

            // 检查是否至少上传了一张图片
            // var hasTypeReport = $('#typeReportFile')[0].files.length > 0 || $('.typeReportImg').length > 0;
            // var hasBatchReport = $('#batchReportFile')[0].files.length > 0 || $('.batchReportImg').length > 0;
            // var hasPackagingImg = $('#packagingImgFile')[0].files.length > 0 || $('.packagingImg').length > 0;
            //
            // if (!hasTypeReport || !hasBatchReport || !hasPackagingImg) {
            //     layer.msg('请上传所有必需的图片！', {icon: 2});
            //     return false;
            // }
            //
            // 显示加载动画
            var loadIndex = layer.load(1, {
                shade: [0.1, '#fff'] // 0.1透明度的白色背景
            });

            // 禁用提交按钮，防止重复提交
            $("#formBtn").attr("disabled", true);

            // 手动提交表单
            var formElement = document.querySelector('form');
            formElement.submit();

            // 返回false阻止默认提交行为，因为我们已经手动提交了
            return false;
        });
    });

    // 图片上传功能
    $(document).ready(function () {
        // 在产产品型式检验报告上传
        $('#typeReportUpload').click(function () {
            $('#typeReportFile').click();
        });

        $('#typeReportFile').change(function () {
            var file = this.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(".typeReportImg").remove();
                    $("#typeReportImg").append('<img src="' + e.target.result + '" class="typeReportImg" style="width: 100px;height: 100px;">');
                };
                reader.readAsDataURL(file);
            }
        });

        // 在产产品的批次检验报告上传
        $('#batchReportUpload').click(function () {
            $('#batchReportFile').click();
        });

        $('#batchReportFile').change(function () {
            var file = this.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(".batchReportImg").remove();
                    $("#batchReportImg").append('<img src="' + e.target.result + '" class="batchReportImg" style="width: 100px;height: 100px;">');
                };
                reader.readAsDataURL(file);
            }
        });

        // 包装图片上传
        $('#packagingImgUpload').click(function () {
            $('#packagingImgFile').click();
        });

        $('#packagingImgFile').change(function () {
            var file = this.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(".packagingImg").remove();
                    $("#packagingImg").append('<img src="' + e.target.result + '" class="packagingImg" style="width: 100px;height: 100px;">');
                };
                reader.readAsDataURL(file);
            }
        });
    });

    // 返回按钮点击事件
    document.getElementById("rollback").addEventListener("click", function () {
        window.history.back(); // 返回上一页
    });

    // 备用提交方法 - 直接绑定到按钮点击事件
    $("#formBtn").click(function (e) {
        // 如果Layui的表单监听器没有处理，则使用备用方法
        setTimeout(function () {
            if (!$("#formBtn").attr("disabled")) {
                // 说明Layui没有处理，使用备用提交方法
                var formElement = document.querySelector('form');
                if (formElement) {
                    // 验证表单
                    var isValid = validateForm();
                    if (isValid) {
                        // 显示加载动画
                        layer.load(1, {
                            shade: [0.1, '#fff']
                        });
                        $("#formBtn").attr("disabled", true);
                        formElement.submit();
                    }
                }
            }
        }, 100);
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        var k = 1024;
        var sizes = ['Bytes', 'KB', 'MB', 'GB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 清除已选文件
    function clearFile() {
        layui.use(['jquery', 'layer'], function () {
            var $ = layui.$;
            var layer = layui.layer;
            layer.confirm('确定要移除这个文件吗？', function (index) {
                $("#filePreview").html('');
                $("#report").val('');
                $("#uploadStatus").html('已取消文件选择');
                // 清空文件输入框，确保可以重新选择相同文件
                $("#fileInput").val('');
                layer.close(index);
            });
        });
    }

    // 移除已上传的文件
    function removeUploadedFile() {
        layui.use(['jquery', 'layer'], function () {
            var $ = layui.$;
            var layer = layui.layer;
            layer.confirm('确定要移除这个文件吗？', function (index) {
                $("#filePreview").html('');
                $("#report").val('');
                $("#uploadStatus").html('已取消文件选择');
                // 清空文件输入框，确保可以重新选择相同文件
                $("#fileInput").val('');
                layer.close(index);
            });
        });
    }


    // 表单验证函数
    function validateForm() {
        var productName = $('input[name="productName"]').val();
        var approvalNumber = $('input[name="approvalNumber"]').val();
        var specification = $('input[name="specification"]').val();
        var dosageForm = $('input[name="dosageForm"]').val();
        var healthFunction = $('input[name="healthFunction"]').val();
        var enterpriseStandard = $('input[name="enterpriseStandard"]').val();
        var applicationMaterials = $('input[name="applicationMaterials"]').val();
        var revisionStatus = $('input[name="revisionStatus"]').val();

        // 检查必填字段
        if (!productName || !approvalNumber || !specification || !dosageForm ||
            !healthFunction || !enterpriseStandard || !applicationMaterials || !revisionStatus) {
            layer.msg('请填写所有必填字段！', {icon: 2});
            return false;
        }

        // 检查是否至少上传了一张图片
        var hasTypeReport = $('#typeReportFile')[0].files.length > 0 || $('.typeReportImg').length > 0;
        var hasBatchReport = $('#batchReportFile')[0].files.length > 0 || $('.batchReportImg').length > 0;
        var hasPackagingImg = $('#packagingImgFile')[0].files.length > 0 || $('.packagingImg').length > 0;

        if (!hasTypeReport || !hasBatchReport || !hasPackagingImg) {
            layer.msg('请上传所有必需的图片！', {icon: 2});
            return false;
        }

        return true;
    }
</script>
</body>
</html>
